package com.example.bookmanage.service.impl;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.example.bookmanage.enums.ResultCode;
import com.example.bookmanage.exception.ServiceException;
import com.example.bookmanage.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    public String uploadFile(MultipartFile file, String directory) {
        String originalFilename = file.getOriginalFilename();
        String extension = null;
        if (originalFilename != null) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = directory + "/" + UUID.fastUUID().toString().replace("-", "") + extension;

        try {
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            return urlPrefix + "/" + fileName;
        } catch (IOException e) {
            throw new ServiceException(ResultCode.FAILED);
        }
    }
}
